package com.pozu.new_retail.controllers;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pozu.new_retail.dao.base.JsonResult;
import com.pozu.new_retail.dao.model.AppSetting;
import com.pozu.new_retail.dao.model.DiscountSetting;
import com.pozu.new_retail.dao.model.Goods;
import com.pozu.new_retail.dao.model.GoodsExt;
import com.pozu.new_retail.dao.model.ShareInfo;
import com.pozu.new_retail.dao.model.ShareRecord;
import com.pozu.new_retail.dao.model.ShoppingCart;
import com.pozu.new_retail.service.AppSettingService;
import com.pozu.new_retail.service.DiscountSettingService;
import com.pozu.new_retail.service.GoodsExtService;
import com.pozu.new_retail.service.GoodsService;
import com.pozu.new_retail.service.ShareInfoService;
import com.pozu.new_retail.service.ShareRecordService;
import com.pozu.new_retail.service.ShoppingCartService;
import com.pozu.new_retail.utils.CodeConstants;
import com.pozu.new_retail.utils.CodeProperties;
import com.pozu.new_retail.utils.Constants;
import com.pozu.new_retail.utils.PayTools;
import com.pozu.new_retail.utils.Tools;

@Controller
public class ShareController {
	
	@Autowired
	private ShareInfoService shareInfoService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsExtService goodsExtService;
	@Autowired
	private ShareRecordService shareRecordService;
	@Autowired
	private DiscountSettingService discountSettingService;
	@Autowired
	private AppSettingService appSettingService;
	
	@ResponseBody
	@RequestMapping(value = "/api/shareInfos", method = RequestMethod.POST)
	public Object add(HttpServletRequest request) throws Exception{
		
		int appId = Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		JsonResult jr = new JsonResult();

		long userId = Long.parseLong(request.getHeader("userId"));
		
		ShareInfo requestShareInfo = Tools.getRequestObject(request, ShareInfo.class);
		
		HashMap<String,Object> hashMap = new HashMap<String,Object>();
		hashMap.put("appId", appId);
		hashMap.put("goodsExtId", requestShareInfo.getGoodsExtId());
		hashMap.put("number", requestShareInfo.getNumber());
		hashMap.put("userId", userId);
		
		ShareInfo info = shareInfoService.queryByMap(hashMap);
		
		if (null != info) {
			
			jr.respCode = CodeConstants.SUCCESS_CODE;
			jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
			jr.respData = info.getShareId();
			
			return jr;
		}
		
		GoodsExt ext = goodsExtService.queryByGoodsExtId(requestShareInfo.getGoodsExtId());
		
		if(null == ext){
			jr.respCode = CodeConstants.GOODSNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.GOODSNOTEXISTED_MSG);
			return jr;
		}
		
		if (ext.getNumber() <= 0) {
			jr.respCode = CodeConstants.GOODSNOTENOUGH_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.GOODSNOTENOUGH_MSG);
			return jr;
		}
		
		Goods goods = goodsService.queryInfoByGoodsId(ext.getGoodsId());
		
		if(null == goods){
			jr.respCode = CodeConstants.GOODSNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.GOODSNOTEXISTED_MSG);
			return jr;
		}
		
		if (goods.getDiscountFlag() == 0 || goods.getSaleType() != 1) {
			jr.respCode = CodeConstants.GOODSSHAREDERROR_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.GOODSSHAREDERROR_MSG);
			return jr;
		}
		
		requestShareInfo.setAppId(appId);
		requestShareInfo.setUserId(userId);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = shareInfoService.saveShareInfo(requestShareInfo);
		
		return jr;
	}
	
	@ResponseBody
	@RequestMapping(value = "/api/shareInfos/link", method = RequestMethod.GET)
	public Object get(HttpServletRequest request) throws Exception{
		
		JsonResult jr = new JsonResult();

		long userId = Long.parseLong(request.getHeader("userId"));
		
		long shareId = Integer.parseInt(request.getParameter("shareId"));
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = shareInfoService.queryLinkedByShareId(userId,shareId);
		
		return jr;
		
	}
	
	@ResponseBody
	@RequestMapping(value = "/api/shareInfos/details", method = RequestMethod.GET)
	public Object getMyShare(HttpServletRequest request) throws Exception{

		JsonResult jr = new JsonResult();

		long shareId = Integer.parseInt(request.getParameter("shareId"));
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = shareInfoService.queryDetailsByShareId(shareId);
		
		return jr;
	}
	
	@ResponseBody
	@RequestMapping(value = "/api/shareInfos/list", method = RequestMethod.GET)
	public Object getList(HttpServletRequest request) throws Exception{

		int appId = Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		JsonResult jr = new JsonResult();

		long userId = Long.parseLong(request.getHeader("userId"));
		
		HashMap<String, Object> map = new HashMap<String, Object>();

		map.put("userId", userId);
		map.put("appId", appId);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = shareInfoService.queryListByUserId(map);
		
		return jr;
	}
	
	/***
	 * 砍价
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/shareInfos/click", method = RequestMethod.PUT)
	public Object click(HttpServletRequest request) throws Exception{
		
		int appId = Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		AppSetting appSetting = appSettingService.queryByAppId(appId);
		
		JsonResult jr = new JsonResult();	
		Map<String, Object> map = Tools.getRequestData(request);	
		//获取用户的openId
		String js_code = map.get("js_code").toString();
		/** 昵称 */
	    String nickName = map.get("nickName").toString();
	    /** 性别0未知1男2女 */
	    Integer gender = Integer.parseInt( map.get("gender").toString());
	    /** 头像 */
	    String avatarUrl = map.get("avatarUrl").toString();
				
		Map<String, String> hashMap = PayTools.getOpenIdAnUUID(js_code,appSetting.getWxAppId(),appSetting.getAppSecret());
				
		String openId = hashMap.get("openId");
		
		if (StringUtils.isEmpty(openId)) {
			jr.respCode = CodeConstants.USERINFONOTGET_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.USERINFONOTGET_MSG);
			return jr;
		}
		
		Long shareId = Long.parseLong(map.get("shareId").toString());//分享的编号
		
		HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
		hashMap2.put("openId", openId);
		hashMap2.put("shareId", shareId);
		
		ShareRecord record = shareRecordService.queryByMap(hashMap2);
		
		if(null != record){
			jr.respCode = CodeConstants.SHARECLICKED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.SHARECLICKED_MSG);
			return jr;
		}
		
		ShareInfo info = shareInfoService.queryByShareId(shareId);
		
		if(null == info){
			jr.respCode = CodeConstants.SHAREDNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.SHAREDNOTEXISTED_MSG);
			return jr;
		}
		
		long time = Constants.SHAREDLIMITTIME -(System.currentTimeMillis()-info.getCreatedTime());//剩余时间
		
		if(info.getState()!=0||time<=0){
			jr.respCode = CodeConstants.SHAREDTIMEOUT_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.SHAREDTIMEOUT_MSG);
			return jr;
		}
		ShareInfo tempInfo = new ShareInfo();
		tempInfo.setShareId(shareId);
		tempInfo.setSharedNumber(info.getSharedNumber()+1);
		
		DiscountSetting discountSetting = discountSettingService.queryByAppId(appId);
		
		if(tempInfo.getSharedNumber() == discountSetting.getShareNumber1()){
			tempInfo.setTicketNumber(discountSetting.getTicketNumber1());
		}else if(tempInfo.getSharedNumber() == discountSetting.getShareNumber2()) {
			tempInfo.setTicketNumber(info.getTicketNumber()+discountSetting.getTicketNumber2() - discountSetting.getTicketNumber1());
		}
		
		shareInfoService.updateShareInfo(tempInfo);
		
		record = new ShareRecord();
		
		record.setOpenId(openId);
		record.setNickName(nickName);
		record.setShareId(shareId);
		record.setAvatarUrl(avatarUrl);
		record.setGender(gender);
		
		shareRecordService.saveShareRecord(record);

		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);

		return jr;
	}
	
	/**
	 * 终止并加入购物车
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/shareInfos/stop", method = RequestMethod.PUT)
	public Object stop(HttpServletRequest request) throws Exception{
				
		int appId = Integer.parseInt(request.getHeader("appId"));//那个小程序
	
		JsonResult jr = new JsonResult();
		
		ShareInfo requestShareInfo = Tools.getRequestObject(request, ShareInfo.class);

		long userId = Long.parseLong(request.getHeader("userId"));
		
		long shareId = requestShareInfo.getShareId();//分享出去的id
		
		ShareInfo info = shareInfoService.queryByShareId(shareId);
		
		if(null == info){
			jr.respCode = CodeConstants.SHAREDNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.SHAREDNOTEXISTED_MSG);
			return jr;
		}
		
		if(info.getShoppingCartId()>0){
			jr.respCode = CodeConstants.SHAREDGOODSINCART_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.SHAREDGOODSINCART_MSG);
			return jr;
		}
		
		GoodsExt ext = goodsExtService.queryByGoodsExtId(info.getGoodsExtId());
		
		if(null == ext){
			jr.respCode = CodeConstants.GOODSNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.GOODSNOTEXISTED_MSG);
			return jr;
		}
		
		if (ext.getNumber() <= 0) {
			jr.respCode = CodeConstants.GOODSNOTENOUGH_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.GOODSNOTENOUGH_MSG);
			return jr;
		}
		
		ShoppingCart cart = new ShoppingCart();
		cart.setUserId(userId);
		cart.setGoodsExtId(info.getGoodsExtId());
		cart.setNumber(info.getNumber());
		cart.setMoney(ext.getPrice());
		
		DiscountSetting discountSetting = discountSettingService.queryByAppId(appId);
		
		if(info.getTicketResult()==1){
			cart.setDiscount(100);
		}else{
			if(info.getSharedNumber() >= discountSetting.getShareNumber1()){
				cart.setDiscount(100-discountSetting.getDiscount1());
			}else if(info.getSharedNumber() >= discountSetting.getShareNumber2()){
				cart.setDiscount(100-discountSetting.getDiscount2());
			}else{
				cart.setDiscount(0);
			}
		}
		cart.setType(2);
		cart.setAppId(appId);
		shoppingCartService.saveShoppingCart(cart);
				
		requestShareInfo.setShoppingCartId(cart.getShoppingCartId());
		requestShareInfo.setState(1);
		
		shareInfoService.updateShareInfo(requestShareInfo);
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		return jr;
	}
	/**
	 * 抽奖
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/api/shareInfos/draw", method = RequestMethod.PUT)
	public Object draw(HttpServletRequest request) throws Exception{
		
		int appId = Integer.parseInt(request.getHeader("appId"));//那个小程序
		
		JsonResult jr = new JsonResult();
		
		ShareInfo requestShareInfo = Tools.getRequestObject(request, ShareInfo.class);

		long userId = Long.parseLong(request.getHeader("userId"));
		
		long shareId = requestShareInfo.getShareId();//分享出去的编号
		
		ShareInfo info = shareInfoService.queryByShareId(shareId);
		
		if(null == info || info.getUserId() != userId){
			jr.respCode = CodeConstants.SHAREDNOTEXISTED_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.SHAREDNOTEXISTED_MSG);
			return jr;
		}
		
		if(info.getTicketNumber() == 0){
			jr.respCode = CodeConstants.SHAREDDRAWERROR_MSG;
			jr.respMsg = CodeProperties.getString(CodeConstants.SHAREDDRAWERROR_MSG);
			return jr;
		}
		
		if(info.getTicketResult() == 1){
			
			jr.respCode = CodeConstants.SUCCESS_CODE;
			jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
			jr.respData = info.getTicketResult();
			
			return jr;	
		}else{
			
			DiscountSetting discountSetting = discountSettingService.queryByAppId(appId);
			

			int num = new Random().nextInt(100);
			if(num < discountSetting.getFreeRate()){
				requestShareInfo.setTicketResult(1);
				requestShareInfo.setTicketNumber(0);
			}else {
				requestShareInfo.setTicketNumber(info.getTicketNumber()-1);
				requestShareInfo.setTicketResult(0);
			}
		}
		
		shareInfoService.updateShareInfo(requestShareInfo);
		
		if(info.getShoppingCartId() > 0 && requestShareInfo.getTicketResult() == 1){
			//已加入购物车则同步下免单信息
			ShoppingCart cart = shoppingCartService.queryByShoppingCartId(info.getShoppingCartId());
			if(null!=cart){
				ShoppingCart tempCart = new ShoppingCart();
				tempCart.setShoppingCartId(info.getShoppingCartId());
				tempCart.setDiscount(100);
				shoppingCartService.updateShoppingCart(tempCart);
			}
		}
		
		jr.respCode = CodeConstants.SUCCESS_CODE;
		jr.respMsg = CodeProperties.getString(CodeConstants.SUCCESS_MSG);
		jr.respData = info.getTicketResult();
		
		return jr;	
	}
	
}
